package com.qf.shop.goods.service.impl;

import com.qf.shop.common.exception.BusinessException;
import com.qf.shop.common.exception.LockStockException;
import com.qf.shop.common.vo.StockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.shop.common.utils.PageUtils;
import com.qf.shop.common.utils.Query;

import com.qf.shop.goods.dao.StockDao;
import com.qf.shop.goods.entity.StockEntity;
import com.qf.shop.goods.service.StockService;
import org.springframework.transaction.annotation.Transactional;


@Service("stockService")
@Slf4j
public class StockServiceImpl extends ServiceImpl<StockDao, StockEntity> implements StockService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<StockEntity> page = this.page(
                new Query<StockEntity>().getPage(params),
                new QueryWrapper<StockEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 扣减库存的时候回出现部分扣减成功，部分扣减失败 --》统一失败
     *
     * @param stockVoList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 这个方法出现的异常只要是Exception的子都需要回滚，默认值RuntimeException
    public Boolean lockStock(List<StockVo> stockVoList) throws LockStockException {
        for (StockVo stockVo : stockVoList) {
            Integer count = baseMapper.lockStock(stockVo.getGid(), stockVo.getCount());
            if (count <= 0) {
                log.debug("扣减库存失败,gid【{}】，count【{}】", stockVo.getGid(), stockVo.getCount());
//                throw new BusinessException("扣减库存失败", 3001);
                throw new LockStockException(3001, "扣减库存失败");
            }
        }
        return true;
    }

    @Override
    public Boolean unLockStock(List<StockVo> stockVoList) {
        for (StockVo stockVo : stockVoList) {
            Integer update = baseMapper.unLockStock(stockVo.getGid(), stockVo.getCount());
            if (update <= 0) {
                // 如果批量释放库存，有部分释放库存失败，不需要事务回滚，优先要考虑库存释放
                log.error("释放库存失败,gid:{},count:{}", stockVo.getGid(), stockVo.getCount());
            }
        }
        return true;
    }

}